package com.example.socialapp.ui.post

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.outlined.InsertComment
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue

/**
 * 动态详情界面
 *
 * @param postId 动态ID
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToUserProfile 导航到用户资料界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PostDetailScreen(
    postId: String,
    onNavigateBack: () -> Unit,
    onNavigateToUserProfile: (String) -> Unit = {}
) {
    // 在实际应用中应从ViewModel获取动态和评论数据
    val post = remember { generateSamplePost(postId) }
    val comments = remember { generateSampleComments(postId) }
    
    var commentText by remember { mutableStateOf("") }
    var showMenu by remember { mutableStateOf(false) }
    var isLiked by remember { mutableStateOf(false) }
    var isBookmarked by remember { mutableStateOf(false) }
    
    val listState = rememberLazyListState()
    
    // 首次加载时如果有评论，滚动到评论部分
    LaunchedEffect(Unit) {
        if (comments.isNotEmpty()) {
            listState.animateScrollToItem(1)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("动态详情") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { isBookmarked = !isBookmarked }) {
                        Icon(
                            imageVector = if (isBookmarked) Icons.Default.Bookmark else Icons.Default.BookmarkBorder,
                            contentDescription = if (isBookmarked) "取消收藏" else "收藏",
                            tint = if (isBookmarked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    IconButton(onClick = { /* 分享动态 */ }) {
                        Icon(
                            imageVector = Icons.Default.Share,
                            contentDescription = "分享"
                        )
                    }
                    IconButton(onClick = { showMenu = true }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                        
                        DropdownMenu(
                            expanded = showMenu,
                            onDismissRequest = { showMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text("举报") },
                                onClick = { 
                                    showMenu = false 
                                    /* 举报动态逻辑 */ 
                                }
                            )
                            DropdownMenuItem(
                                text = { Text("复制文本") },
                                onClick = { 
                                    showMenu = false 
                                    /* 复制动态文本逻辑 */ 
                                }
                            )
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        bottomBar = {
            CommentInputBar(
                value = commentText,
                onValueChange = { commentText = it },
                onSendClick = {
                    if (commentText.isNotBlank()) {
                        // 发送评论逻辑（在实际应用中应与ViewModel交互）
                        commentText = ""
                    }
                }
            )
        }
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
            state = listState
        ) {
            // 动态内容
            item {
                PostDetailItem(
                    post = post,
                    isLiked = isLiked,
                    onLikeClick = { isLiked = !isLiked },
                    onAuthorClick = { onNavigateToUserProfile(post.authorId) }
                )
                
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                
                // 评论标题
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Outlined.InsertComment,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "评论 (${comments.size})",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
            
            // 评论列表
            if (comments.isEmpty()) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "暂无评论，快来发表你的看法吧",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                }
            } else {
                items(comments) { comment ->
                    CommentItem(
                        comment = comment,
                        onAuthorClick = { onNavigateToUserProfile(comment.authorId) }
                    )
                    Divider(
                        modifier = Modifier.padding(start = 72.dp, end = 16.dp),
                        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
                    )
                }
                
                // 底部空间，防止内容被输入框遮挡
                item {
                    Spacer(modifier = Modifier.height(16.dp))
                }
            }
        }
    }
}

/**
 * 动态详情项
 */
@Composable
private fun PostDetailItem(
    post: PostDetail,
    isLiked: Boolean,
    onLikeClick: () -> Unit,
    onAuthorClick: () -> Unit
) {
    Column(modifier = Modifier.padding(16.dp)) {
        // 作者信息
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.clickable { onAuthorClick() }
        ) {
            // 头像
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(getColorForName(post.authorName)),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = post.authorName.first().toString(),
                    style = MaterialTheme.typography.titleMedium,
                    color = Color.White
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            Column {
                Text(
                    text = post.authorName,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = post.formattedTime,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 动态内容
        Text(
            text = post.content,
            style = MaterialTheme.typography.bodyLarge
        )
        
        // 如果有图片，这里应该显示图片
        // 实际应用中应加载真实图片
        if (post.hasImage) {
            Spacer(modifier = Modifier.height(16.dp))
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(MaterialTheme.colorScheme.secondaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "图片内容",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 交互栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = onLikeClick) {
                    Icon(
                        imageVector = if (isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        tint = if (isLiked) Color.Red else MaterialTheme.colorScheme.onSurface
                    )
                }
                Text(
                    text = (post.likes + (if (isLiked && !post.isLiked) 1 else 0)).toString(),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = { /* 评论逻辑 */ }) {
                    Icon(
                        imageVector = Icons.Outlined.InsertComment,
                        contentDescription = "评论"
                    )
                }
                Text(
                    text = post.comments.toString(),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = { /* 分享逻辑 */ }) {
                    Icon(
                        imageVector = Icons.Default.Share,
                        contentDescription = "分享"
                    )
                }
                Text(
                    text = post.shares.toString(),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

/**
 * 评论项
 */
@Composable
private fun CommentItem(
    comment: Comment,
    onAuthorClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        // 头像
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(getColorForName(comment.authorName))
                .clickable { onAuthorClick() },
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = comment.authorName.first().toString(),
                style = MaterialTheme.typography.titleMedium,
                color = Color.White
            )
        }
        
        Spacer(modifier = Modifier.width(12.dp))
        
        Column(modifier = Modifier.weight(1f)) {
            // 作者信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.clickable { onAuthorClick() }
            ) {
                Text(
                    text = comment.authorName,
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text(
                    text = comment.formattedTime,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium
            )
            
            // 评论交互区域（点赞等）
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 4.dp),
                horizontalArrangement = Arrangement.End
            ) {
                Text(
                    text = "回复",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline,
                    modifier = Modifier.clickable { /* 回复逻辑 */ }
                )
                
                Spacer(modifier = Modifier.width(16.dp))
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { /* 点赞逻辑 */ }
                ) {
                    Icon(
                        imageVector = Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        modifier = Modifier.size(16.dp),
                        tint = MaterialTheme.colorScheme.outline
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = comment.likes.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        }
    }
}

/**
 * 评论输入栏
 */
@Composable
private fun CommentInputBar(
    value: String,
    onValueChange: (String) -> Unit,
    onSendClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(0.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier.weight(1f),
                placeholder = { Text("添加评论...") },
                keyboardOptions = KeyboardOptions(
                    capitalization = KeyboardCapitalization.Sentences,
                    keyboardType = KeyboardType.Text,
                    imeAction = ImeAction.Send
                ),
                keyboardActions = KeyboardActions(
                    onSend = { onSendClick() }
                ),
                maxLines = 3,
                shape = RoundedCornerShape(24.dp),
                singleLine = true
            )
            
            Spacer(modifier = Modifier.width(8.dp))
            
            IconButton(
                onClick = onSendClick,
                enabled = value.isNotBlank()
            ) {
                Icon(
                    imageVector = Icons.Default.Send,
                    contentDescription = "发送",
                    tint = if (value.isNotBlank()) 
                        MaterialTheme.colorScheme.primary 
                    else 
                        MaterialTheme.colorScheme.outline
                )
            }
        }
    }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 动态详情数据类
 */
data class PostDetail(
    val id: String,
    val authorId: String,
    val authorName: String,
    val content: String,
    val timestamp: Long,
    val likes: Int,
    val comments: Int,
    val shares: Int,
    val hasImage: Boolean,
    val isLiked: Boolean
) {
    val formattedTime: String
        get() {
            val sdf = SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.getDefault())
            return sdf.format(Date(timestamp))
        }
}

/**
 * 评论数据类
 */
data class Comment(
    val id: String,
    val postId: String,
    val authorId: String,
    val authorName: String,
    val content: String,
    val timestamp: Long,
    val likes: Int
) {
    val formattedTime: String
        get() {
            val sdf = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
            return sdf.format(Date(timestamp))
        }
}

/**
 * 生成示例动态
 */
private fun generateSamplePost(postId: String): PostDetail {
    return PostDetail(
        id = postId,
        authorId = "10086",
        authorName = "张三",
        content = "今天去了云南大理，风景真的太美了！蓝天白云下的洱海像一面镜子，倒映着苍山的倩影。远处的村庄掩映在绿树之中，宁静而祥和。在古城的小巷中漫步，感受着浓厚的白族文化氛围，品尝了正宗的白族三道茶，真是一次难忘的旅行体验。有机会一定要再来！",
        timestamp = System.currentTimeMillis() - 2 * 60 * 60 * 1000,
        likes = 57,
        comments = 13,
        shares = 5,
        hasImage = true,
        isLiked = false
    )
}

/**
 * 生成示例评论
 */
private fun generateSampleComments(postId: String): List<Comment> {
    val currentTime = System.currentTimeMillis()
    val hourInMillis = 60 * 60 * 1000L
    
    return listOf(
        Comment(
            id = "1",
            postId = postId,
            authorId = "10087",
            authorName = "李四",
            content = "大理确实很美，我上个月也去了，印象最深的是苍山的日落和洱海的日出，简直美不胜收！",
            timestamp = currentTime - 1 * hourInMillis,
            likes = 12
        ),
        Comment(
            id = "2",
            postId = postId,
            authorId = "10088",
            authorName = "王五",
            content = "羡慕啊，有没有推荐的住宿和美食？准备下个月去",
            timestamp = currentTime - 45 * 60 * 1000,
            likes = 5
        ),
        Comment(
            id = "3",
            postId = postId,
            authorId = "10089",
            authorName = "赵六",
            content = "照片呢？这么美的风景怎么能不发照片呢！",
            timestamp = currentTime - 30 * 60 * 1000,
            likes = 8
        ),
        Comment(
            id = "4",
            postId = postId,
            authorId = "10090",
            authorName = "钱七",
            content = "我收藏了好几个大理的攻略，需要的话可以发给你",
            timestamp = currentTime - 15 * 60 * 1000,
            likes = 3
        ),
        Comment(
            id = "5",
            postId = postId,
            authorId = "10091",
            authorName = "孙八",
            content = "我是大理人，欢迎你们来玩，有什么问题可以问我",
            timestamp = currentTime - 5 * 60 * 1000,
            likes = 20
        )
    )
} 